<template>
  <div class="w_full p_relative h_full">
    <chat-header :rowItem='friendItem' />
    <!-- <div class="w_header flexbetween">
      <div>
        <template v-if="friendItem">
          <span class="f-14 c_222333">{{ friendItem.nickname }}</span>
          <span class="f-12 c_f90 pl-5">@yunyy</span>
          <el-popover
            placement="top"
            width="320"
            v-model="visible">
            <el-form :model="nameform" ref="nameform" label-position="top" class="nameform">
              <el-form-item label="修改备注" prop="name">
                <el-input v-model="nameform.name" size="small" placeholder="请输入备注"></el-input>
              </el-form-item>
            </el-form>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="visible = false">取消</el-button>
              <el-button type="primary" size="mini" @click="handleEidtName">确定</el-button>
            </div>
            <i class="el-icon-edit-outline f-14 commhover c_primary" slot="reference"></i>
          </el-popover>
        </template>
      </div>
      <div class="c_primary f-14">
        查看更多聊天消息 <i class="el-icon-arrow-right"></i>
      </div>
    </div> -->
    <div class="chat-content">
      <div class="msg-div w_full h_full" :id="'msg-div' + nowStr">
        <!-- 加载更多 -->
        <div v-loading="loading"></div>
        <div v-if="!loading">
          <div v-if="loadMore" @click="loadingMore" class="flexcenter">
            <span class="f-14 c_primary pt-6">查看更多消息</span>
          </div>
          <div v-if="!loadMore" class="flexcenter">
            <span class="f-14 pt-6">没有更多了</span>
          </div>
        </div>
        <msg-main
          ref="messagemain"
          :messageList="messageList"
          :loadMore="loadMore"
          :loading="loading"
          @loadingMore="loadingMore"
        />
      </div>
    </div>
    <div class="w_bottom bg_fff">
      <chat-tool ref="chatTool" @sendMessage='sendChatItem' />
    </div>
  </div>
</template>
<script>
import MsgMain from "./components/MsgMain.vue";
import { mapState } from "vuex";
import EmojiPop from '@/components/EmojiPop';
import ChatHeader from './components/ChatHeader.vue';
import ChatTool from './components/ChatTool.vue'
export default {
  data() {
    return {
      isTip: false,
      message: "",
      messageList: [
        {
          sendFrom: 1,
          type: "text",
          content: "消息内容",
          createTime: "2023-12-20:20:52:00",
        },
        {
          sendFrom: 2,
          type: "text",
          content: "消息内容2",
          createTime: "2023-12-20:20:52:00",
        },
        {
          sendFrom: 1,
          type: "image",
          url: "https://cdn-qyb-hz.wxb.com/u/5424982/qyb/20240104/4e4ce81831d71c426db091b88e3de470.jpg",
          createTime: "2023-12-20:20:52:00",
        },
        {
          sendFrom: 2,
          type: "image",
          url: "https://cdn-qyb-hz.wxb.com/u/5424982/qyb/20240104/4e4ce81831d71c426db091b88e3de470.jpg",
          createTime: "2023-12-20:20:52:00",
        },
      ],
      nowStr: new Date().getTime(), // 当前的时间戳，用于每次消息加载后，回到原位置；具体见 :id="'msg-div' + nowStr" 处
      queryParams: {
        pageNo: 1, // 当前页数
        pageSize: 14, // 每页显示多少条
        accountId: undefined,
      },
      loadMore: true, // 是否可以加载更多
      loading: false, //状态加载
      nameform:{
        name:''
      },
      visible: false
    };
  },
  created() {
    this.scrollToBottom();
  },
  computed: {
    ...mapState({
      chatmsg: (state) => state.chat.chatmsg,
      sendChatList: (state) => state.chat.sendChatList,
    }),
  },
  watch:{
    chatmsg(val){
      if(val){
        this.message = val
        this.$store.commit("chat/SET_CHATMSG", '');
      }
    },
    // 监听右侧话术点击发送消息
    sendChatList(val){
      if(val){
        console.log(val)
        this.sendTrick(val)
      }
    }
  },
  props: {
    userItem: {
      //用户
      type: Object,
      default: null,
    },
    friendItem: {
      //好友
      type: Object,
      default: null,
    },
  },
  components: {
    MsgMain,
    EmojiPop,
    ChatHeader,
    ChatTool
  },
  methods: {
    getPage(page, params) {
      this.loading = true;
      getMessagePage(
        Object.assign(
          {
            pageNo: page.pageNo,
            pageSize: page.pageSize,
            userId: this.userId,
            accountId: page.accountId,
          },
          params
        )
      ).then((response) => {
        // 计算当前的滚动高度
        const msgDiv = document.getElementById("msg-div" + this.nowStr);
        let scrollHeight = 0;
        if (msgDiv) {
          scrollHeight = msgDiv.scrollHeight;
        }

        // 处理数据
        const data = response.data.list.reverse();
        this.messageList = [...data, ...this.messageList];
        this.loading = false;
        if (data.length < this.queryParams.pageSize || data.length === 0) {
          this.loadMore = false;
        }
        this.queryParams.pageNo = page.pageNo;
        this.queryParams.pageSize = page.pageSize;

        // 滚动到原来的位置
        if (this.queryParams.pageNo === 1) {
          // 定位到消息底部
          this.scrollToBottom();
        } else if (data.length !== 0) {
          // 定位滚动条
          this.$nextTick(() => {
            if (scrollHeight !== 0) {
              msgDiv.scrollTop =
                document.getElementById("msg-div" + this.nowStr).scrollHeight -
                scrollHeight -
                100;
            }
          });
        }
      });
    },

    // 加载更多
    loadingMore() {
      this.queryParams.pageNo++;
      this.getPage(this.queryParams);
    },

    /** 定位到消息底部 */
    scrollToBottom: function () {
      this.$nextTick(() => {
        let div = document.getElementById("msg-div" + this.nowStr);
        div.scrollTop = div.scrollHeight;
      });
    },

    handleTip(val) {
      console.log("val:", val);
    },

    //选择表情包
    chooseEmoji(icon) {
      var elInput = document.getElementById("message");
      var startPos = elInput.selectionStart;
      var endPos = elInput.selectionEnd;
      var text = elInput.value;
      if (startPos === undefined || endPos === undefined) {
        return;
      }
      var result =
        text.substring(0, startPos) + icon.name + text.substring(endPos);
      //重新定义光标位置
      elInput.focus();
      elInput.selectionStart = startPos + icon.name.length;
      elInput.selectionEnd = startPos + icon.name.length;
      elInput.value = result;
      this.message = result;
    },

    // sendMessage(item){
      // if (!this.message.trim()) return;
      // let item = {
      //   sendFrom: 1,
      //   type: "text",
      //   content: this.message,
      //   createTime: this.parseTime(new Date()),
      // }
      // console.log('发送消息：', item)
      // this.sendChatItem(item)
    // },

    sendChatItem(item) {
      this.messageList.push(item)
      this.scrollToBottom();
      // this.message = "";
      this.$refs.chatTool&&this.$refs.chatTool.clearMessage()
    },

    // 话术里面的发送消息
    sendTrick(arr){
      if(arr.length){
        console.log('发送了----')
        arr.forEach(item => {
          item.sendFrom = 1
          item.createTime = this.parseTime(new Date())
          this.sendChatItem(item)
        })
      }
    },

    // 修改备注
    handleEidtName(){
      this.visible = false
    },
  },
};
</script>
<style lang="scss" scoped>
.w_header {
  height: 52px;
  padding: 0 17px;
  border-bottom: 1px solid #e0e0e0;
}
.w_bottom {
  position: absolute;
  bottom: 0;
  height: 221px;
  left: 0;
  right: 0;
  border-top: 1px solid #e0e0e0;
}
.w_tool {
  //   height: 22px;
  padding: 10px;
}
.nobodersw {
  ::v-deep .el-switch__core {
    border-color: transparent !important;
  }
}
.icontool {
  width: 20px;
  height: 20px;
}
.footbtns {
  padding: 10px 16px 16px;
}
.textareabox {
  position: relative;
  flex: 1 1;
}
.inputnobord {
  ::v-deep .el-textarea__inner {
    border: 0;
  }
}

.chat-content {
  position: absolute;
  top: 52px;
  bottom: 220px;
  left: 0;
  right: 0;
}
.msg-div {
  height: 100%;
  overflow: auto;
}
</style>
